package cn.easybuy.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import cn.easybuy.dao.BaseDao;
import cn.easybuy.dao.UserDao;
import cn.easybuy.entity.User;

public class UserDaoImpl extends BaseDao implements UserDao {

	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	@Override
	public int add(User user) {
		int result=0;
    	try {
    		
    		conn = super.getConnection();
    		
    		String sql=" INSERT into easybuy_user(loginName,userName,password,sex,identityCode,email,mobile) values(?,?,?,?,?,?,?) ";
    		
    		pstmt = conn.prepareStatement(sql);
    		
    		pstmt.setObject(1, user.getLoginName());
    		pstmt.setObject(2, user.getUserName());
    		pstmt.setObject(3, user.getPassword());
    		pstmt.setObject(4, user.getSex());
    		pstmt.setObject(5, user.getIdentityCode());
    		pstmt.setObject(6, user.getEmail());
    		pstmt.setObject(7, user.getMobile());

    		result = pstmt.executeUpdate();
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	super.closeAll(conn, pstmt, rs);
        }
    	return result;
	}

	@Override
	public User findUserByLoginName(String loginName) {
		User user = null;
		
		try {
			conn = super.getConnection();
			String sql = "select * from easybuy_user where loginName=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setObject(1, loginName);
			rs = pstmt.executeQuery();
			
			if (rs.next()) {
				user = new User();
		        user.setLoginName(rs.getString("loginName"));
		        user.setUserName(rs.getString("userName"));
		        user.setPassword(rs.getString("password"));
		        user.setSex(rs.getInt("sex"));
		        user.setIdentityCode(rs.getString("identityCode"));
		        user.setEmail(rs.getString("email"));
		        user.setMobile(rs.getString("mobile"));
		        user.setType(rs.getInt("type"));
		        user.setId(rs.getInt("id"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
        	super.closeAll(conn, pstmt, rs);
        }
		return user;
	}

}
